<!-- 饼图 -->
<template>
  <el-card>
    <template #header> 剧本情景分类饼图 </template>
    <div :id="id" :class="className" :style="{ height, width }"></div>
  </el-card>
</template>

<script setup lang="ts">
import { reqCategoryList, reqGetCategoryId } from "@/api/category/index";
import * as echarts from "echarts";

const props = defineProps({
  id: {
    type: String,
    default: "pieChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});
const options = {
  grid: {
    left: "2%",
    right: "2%",
    bottom: "10%",
    containLabel: true,
  },
  legend: {
    top: "bottom",
    textStyle: {
      color: "#999",
    },
  },
  series: [
    {
      name: "Nightingale Chart",
      type: "pie",
      radius: [30, 60],
      center: ["50%", "40%"],
      // roseType: "area",
      itemStyle: {
        borderRadius: 1,
        color: function (params: any) {
          //自定义颜色
          const colorList = [
            "#409EFF",
            "#67C23A",
            "#E6A23C",
            "#F56C6C",
            "#F42C7B",
            "#52C54A",
          ];
          return colorList[params.dataIndex];
        },
      },
      data: [],
    },
  ],
};

const dataArr = ref<any>([]);
const chart = ref<any>("");

// 获取分类数据
const getCategoryList = async () => {
  let result = await reqCategoryList({ page: 1, pageSize: 10, type: 1 });
  let data;
  result.rows.forEach((item) => {
    data = { id: item.id, name: item.cate_name };
    // options.series[0].data.push(data);
    dataArr.value.push(data);
  });
  let result2 = await reqGetCategoryId();
  dataArr.value.forEach((item: any) => {
    item.value = result2.reduce((total, cateItem) => {
      if (cateItem.cate_id == item.id) {
        total += 1;
      }
      return total;
    }, 0);
  });
  delete dataArr.value.id;
  options.series[0].data = dataArr.value;
  // console.log(options.series[0].data);
  // console.log(result2);
};

onMounted(async () => {
  await getCategoryList();
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );

  chart.value.setOption(options);

  window.addEventListener("resize", () => {
    chart.value.resize();
  });
});

onActivated(() => {
  if (chart.value) {
    chart.value.resize();
  }
});
</script>
